/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.meuevento.business.user;

import com.meuevento.business.event.Event;
import com.meuevento.business.general.CrudService;
import com.meuevento.util.ErrorManager;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
//import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

/**
 *
 * @author Fernando Arena Varella (favarella@inf.ufrgs.br)
 */
@Stateless
public class UserService {
    
    @EJB CrudService<User> crudService;
    @EJB CrudService<Event> crudEventService;

    @PersistenceContext EntityManager em;

    public List<User> listUsers(){
        System.out.println("Listing all users...");
        List<User> users = crudService.findAll(User.class);
        for (User user : users) {
            System.out.println("User " + user.getUserId() + " - " + user.getUsername());
        }
        return users;
    }

    public User findByNameAndPass(String username, String password){
//       CriteriaBuilder cb = em.getCriteriaBuilder();
//        QueryBuilder cb = em.getQueryBuilder();

//        CriteriaQuery<User> c = cb.createQuery(User.class);
//        Root<User> u = c.from(User.class);
//
//        Predicate pUSERNAME = cb.equal(u.get("username"), username);
//        Predicate pPASS = cb.equal(u.get("password"), password);
//        c.where(cb.and(pUSERNAME, pPASS));
//
//        TypedQuery<User> q = em.createQuery(c);

//        return q.getSingleResult();
        //TODO: implementar
        return null;

    }

    public User insertUser(User user){
        try{
        crudService.create(user);
        }catch(Exception ex){
            ErrorManager.generateError(ex.getMessage(), "problema ao inserir usuário:"+user.getUsername());
            ex.printStackTrace();
            return null;
        }
        return user;
    }
    public void addEvent(Event event, User user) {
//       ArrayList<Event> eventos = new ArrayList<Event>();
//       eventos.add(event);
//     user.setEvents(eventos);
        user.getEvents().add(event);
        crudService.update(user);
        crudEventService.update(event);
    }

}
